import axios from 'axios';
import UtilVar from "@/config/UtilVar";
import router from '@/router'
import { getAuthToken, setAuthToken, isTokenExpired } from '@/utils/auth';

let baseUrl = UtilVar.baseUrl
const CancelToken = axios.CancelToken;
export { baseUrl };

// 添加请求拦截器
axios.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么 传token
    let token = localStorage.getItem("token");
    // 后台管理接口使用 access_token
    let adminToken = getAuthToken(); // 使用新的认证方法
    
    config.headers.common['Content-Type'] = "application/json;charset=utf-8";
    
    // 如果是后台管理接口，使用 Authorization Bearer token
    if (config.url && config.url.startsWith('/admin')) {
        if (adminToken) {
            config.headers.common['Authorization'] = `Bearer ${adminToken}`;
        }
    } else {
        // 大屏接口使用 token
        config.headers.common['token'] = token;
    }
    
    return config;
}, function (error) {
    // 对请求错误做些什么
    console.log(error)
    return Promise.reject(error);
});

// 添加响应拦截器
axios.interceptors.response.use(response => {
    // 对响应数据做点什么
    const res = response.data;
    
    // 根据返回的code值来做不同的处理
    if (res.code !== 200) {
        // 特殊错误处理
        if (res.code === 401) {
            // 未认证，清除Token并跳转到登录页
            setAuthToken(null);
            if (router.currentRoute.path !== '/admin/login') {
                router.push('/admin/login');
            }
        }
        return Promise.reject(new Error(res.message || 'Error'));
    } else {
        return res;
    }
}, error => {
    if (error.response) {
        switch (error.response.status) {
            case 401:
                // 未授权，清除Token并跳转到登录页
                setAuthToken(null);
                if (router.currentRoute.path !== '/admin/login') {
                    router.push('/admin/login');
                }
                break;
            case 403:
                // 禁止访问，显示权限不足提示
                console.error('权限不足');
                break;
            default:
                // 其他错误
                console.error('系统错误');
        }
    } else {
        // 网络错误
        console.error('网络连接失败');
    }
    return Promise.reject(error);
});

let configs_ENC = {
    headers: { 'enc': UtilVar.ENC }
}
//处理是否加密数据
let isEncryptionParam = (params) => {
    return params

}
export const GET = async (url, params) => {
    try {
        params = isEncryptionParam(params)
        const data = await axios.get(`${baseUrl}${url}`, {
            params: params,
            headers: configs_ENC.headers
        }, configs_ENC);
        return data;
    } catch (error) {
        return error;
    }
}
//没有基地址 访问根目录下文件

export const GETNOBASE = async (url, params) => {
    try {
        const data = await axios.get(url, {
            params: params,
        });
        return data;
    } catch (error) {
        return error;
    }
}
export const POST = async (url, params) => {
    try {
        params = isEncryptionParam(params)
        const data = await axios.post(`${baseUrl}${url}`, params, configs_ENC);
        return data;
    } catch (error) {
        return error;
    }
}
export const PUT = async (url, params) => {
    try {
        params = isEncryptionParam(params)
        const data = await axios.put(`${baseUrl}${url}`, params, configs_ENC);
        return data;
    } catch (error) {
        return error;
    }
}
export const DELETE = async (url, params) => {
    // console.log(params)
    try {
        params = isEncryptionParam(params)
        const data = await axios.delete(`${baseUrl}${url}`, { data: params, headers: configs_ENC.headers }, configs_ENC);
        return data;
    } catch (error) {
        return error;
    }
}


/**
 * @文件类型提交方法
 */
let configs = {
    headers: { 'Content-Type': 'multipart/form-data' },

}
export const FILESubmit = async (url, params, config = {}) => {
    try {
        const response = await axios.post(`${baseUrl}${url}`, params, {
            ...configs,
            cancelToken: new CancelToken(function executor(c) {
                config && config.setCancel && config.setCancel(c)
            }),
            onUploadProgress: (e) => {
                if (e.total > 0) {
                    e.percent = e.loaded / e.total * 100;
                }
                // console.log(config)
                config && config.onProgress && config.onProgress(e)
            },

        });
        // 确保总是返回一个值
        if (response && response.data) {
            return response.data;
        } else {
            // 如果没有有效的响应数据，返回一个默认的成功响应
            return {
                code: 200,
                message: "success",
                data: null
            };
        }
    } catch (err) {
        console.error('FILESubmit error:', err);
        // 当出现网络错误或其他异常时，返回一个标准的错误对象
        return {
            code: 500,
            message: '网络错误或服务器异常: ' + (err.message || ''),
            data: null
        };
    }
}

/**
 * 下载文档流
 * @param {config.responseType} 下载文件流根据后端 配置   arraybuffer || blod
 */
export const FILE = async (config = {}, body, params) => {
    try {
        const response = await axios({
            method: config.method || 'get',
            url: `${baseUrl}${config.url}`,
            data: body,
            params: params,
            responseType: config.responseType || 'blob',
            onDownloadProgress: (e) => {
                // console.log(e,e.currentTarget)
                // if (e.currentTarget.response.size > 0) {
                //     e.percent = e.loaded / e.currentTarget.response.size * 100;
                // }
                // event.srcElement.getResponseHeader('content-length')
                config.onProgress && config.onProgress(e)
            },
        });
        // 返回完整的响应对象，包含headers信息
        return response;
    } catch (err) {
        return err;
    }
}